package com.bpms.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * http通信工具类
 * @author menlin
 *
 */
public class HttpUtil {

	/**
	 * post方式提交
	 * @param url 请求路径
	 * @param map 参数
	 * @return
	 * @throws Exception 
	 */
	public static String postRequest(String url, Map<String, String> map) throws Exception{
		String body = null;
		HttpClient client = new DefaultHttpClient();
		// 创建post
		HttpPost post = new HttpPost(url);
		// 获取参数
		Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
		HttpResponse response;
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		try {
			while(it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			// 设置参数
			post.setEntity(new UrlEncodedFormEntity(list));
			// 发送请求
			response = client.execute(post);
			// 获取返回数据
			HttpEntity resEntity = response.getEntity();
			body = EntityUtils.toString(resEntity);
			if (resEntity != null) 
				EntityUtils.consume(resEntity);

		} finally {
			client.getConnectionManager().shutdown();
		}
		return body;
	}
	
	/**
	 * 通过二维码获取付款人账号、凭证号、交换行号
	 * @param IMGDATA
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> checkQuickMark(String IMGDATA) throws Exception {
		String url = Param.getValue("ATMP", "atmp_chequesellpart_path");
		Map<String, String> map = new HashMap<String, String>();
		map.put("data", IMGDATA);
		String result = HttpUtil.postRequest(url, map);
		if ("0000".equals(result)) {
			return null;
		}
		JSONObject jret = new JSONObject(result);
		JSONArray ja = jret.optJSONArray("list");
		Map<String, String> r = new HashMap<String, String>();
		JSONObject jo = ja.optJSONObject(0);
		r.put("DRAWEEACCNO", jo.optString("ACCOUNT")); // 付款人账号(开户人账号)
		r.put("PINGZHENGHAO", jo.optString("CERTNUM")); // 凭证号
		r.put("EXCHANGEBANKNO", jo.optString("BANKID")); // 交换行号
		return r;
	}
	
	public static void main (String arg[]) {
		String url = "http://22.202.32.69:8080/EWM/checkEWM.do";
		Map<String, String> map = new HashMap<String, String>();
		map.put("data", "18D2F786A5D6A34DA2502F42BCD542EB");
//		map.put("hehe", "hehe");
		try {
			String s = HttpUtil.postRequest(url, map);
			System.out.println(s);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
